import getConfig from 'next/config';
import { QF } from '@dm/http_request';
import axios from 'axios';

/**
 * 创建客户端端请求对象
 * @param baseURL 域名
 * @returns
 */
function createClientFetch(baseURL = '') {
  const request = new QF(baseURL);
  return request;
}
/**
 * 创建服务器端请求对象
 * @param baseURL 域名
 * @returns
 */
function createServerFetch(baseURL = '') {
  const request = new QF(baseURL);
  return request;
}
/**
 * 创建请求对象
 * @param baseUrl 域名
 * @returns
 */
function createFetch(baseUrl = '') {
  if (typeof window === 'undefined') {
    return createServerFetch(baseUrl);
  }
  return createClientFetch(baseUrl);
}
/**
 * 居友会后端接口
 * @returns
 */
export const appFriendFetch = () => {
  const {
    publicRuntimeConfig: { baseHost },
  }: { publicRuntimeConfig: EnvParamsType } = getConfig();
  return createFetch(`${baseHost}/dw-friend-application`);
};
export const baseFetch = () => {
  return createFetch('/api');
};
/**
 * 钉钉开放接口网关
 * @returns Axios Instance
 */
export const dingtalkOApiFetch = () => {
  // 获取钉钉开放接口域名
  const {
    publicRuntimeConfig: { dingtalkHost },
  }: { publicRuntimeConfig: EnvParamsType } = getConfig();
  // 创建axios请求对象
  const instance = axios.create({ baseURL: dingtalkHost });
  // 处理响应数据
  instance.interceptors.response.use((res) => res.data);
  return instance;
};

/**
 * gitlab开放接口网关
 * @returns Axios Instance
 */
export const gitlabOApiFetch = () => {
  // 获取gitlab开放接口域名
  const {
    publicRuntimeConfig: { gitlabHost },
  }: { publicRuntimeConfig: EnvParamsType } = getConfig();
  // 创建axios请求对象
  const instance = axios.create({ baseURL: `${gitlabHost}/api/v4` });
  // 处理响应数据
  instance.interceptors.response.use((res) => res.data);
  return instance;
};

/**
 * 调用sonar接口。代码质量检查
 */
export const sonarOApiFetch = () => {
  const {
    publicRuntimeConfig: { sonarHost },
  }: { publicRuntimeConfig: EnvParamsType } = getConfig();
  // 创建axios请求对象
  const instance = axios.create({ baseURL: sonarHost });
  // 处理响应数据
  instance.interceptors.response.use((res) => res.data);
  return instance;
};
